import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_deer/database/tables.dart';
import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/ui/live/gun_grid_item.dart';
import 'package:flutter_deer/util/input_formatter/mny_format.dart';
import 'package:flutter_deer/util/socket/mdc_provider.dart';
import 'package:flutter_deer/util/user_config_manager.dart';
import 'package:get/get.dart';


/// 全屏自适应页面，GridView 自适应一行 4 个子项，填满父容器宽度
class GunLivePage extends StatefulWidget {
  const GunLivePage({super.key});

  @override
  State<GunLivePage> createState() => _GunLivePageState();
}

class _GunLivePageState extends State<GunLivePage> with AutomaticKeepAliveClientMixin<GunLivePage> {
  final RxList<GunGridBean> _gunList = <GunGridBean>[].obs;

  int get _spanCount => _gunList.length <= 16
      ? 4
      : _gunList.length <= 25
          ? 5
          : 6;
  final double _padding = 8.0;

  final mdcProvider = Get.find<MdcProvider>();
  StreamSubscription<AppOrderBean>? _subscription;

  // 动态更新指定位置的 item 内容
  void updateItem(AppOrderBean newValue) {
    final gun = _gunList.firstWhereOrNull((element) => element.nzl == newValue.nzl);
    if (gun != null) {
      gun
        ..status = newValue.sta
        ..money = newValue.mny.toYuan
        ..vol = newValue.vol.toYuan;
      _gunList.refresh();
    }
  }

  @override
  void initState() {
    super.initState();
    print('GunLivePage initState');
    _subscription = mdcProvider.stateStream.listen((event) {
      updateItem(event);
    });

    UserConfigManager.getOilGuns().forEach((oils) {
      oils.shelfList?.forEach((shelf) {
        _gunList.add(GunGridBean()
          ..nzl = shelf.shelfNo ?? 0
          ..oilName = oils.goodsSkuName ?? ''
          ..status = 0
          ..price = oils.formatPrice);
      });
    });
    _gunList.sort((a, b) {
      return a.nzl.compareTo(b.nzl);
    });
  }

  @override
  void dispose() {
    print('GunLivePage dispose');
    _subscription?.cancel();
    super.dispose();
  }

  Widget _buildGridItem(GunGridBean item) {
    return GunGridItem(bean: item);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.grey,
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: LayoutBuilder(
          builder: (context, constraints) {
            // 动态计算每个item的宽高
            final double itemWidth = (constraints.maxWidth - _spanCount * _padding) / _spanCount;
            final double itemHeight = (constraints.maxHeight - _spanCount * _padding) / _spanCount;
            return Obx(() => GridView.builder(
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: _spanCount,
                    childAspectRatio: itemWidth / itemHeight, // 1:1 正方形
                    mainAxisSpacing: _padding,
                    crossAxisSpacing: _padding,
                  ),
                  itemCount: _gunList.length,
                  itemBuilder: (context, index) {
                    return _buildGridItem(_gunList[index]);
                  },
                ));
          },
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
